//
//  YWResourceManager.m
//  maintain
//
//  Created by 郑想 on 15/10/27.
//  Copyright © 2015年 ewin. All rights reserved.
//

#import "YWResourceManager.h"
#import "YWConst.h"
#import "YWMacro.h"
#import "YWPicture.h"
#import "YWDBTool.h"
#import "YWCommonTool.h"
#import "UIImage+ProportionalFill.h"
#import "YWAliyunOSSManager.h"
#import "YWLoginTool.h"
#import "YWPatrolPicture.h"

@interface YWResourceManager ()
@property (nonatomic, strong) NSFileManager* fileManager;
@end

@implementation YWResourceManager

YWSingletonM(Manager)

- (NSFileManager*)fileManager
{
    if (!_fileManager) {
        _fileManager = [NSFileManager defaultManager];
    }
    return _fileManager;
}

- (NSString*)saveDataToCacheStorage:(NSData*)data withResourcePath:(NSString*)fileName
{
    BOOL ret = NO;
    if (!data || !fileName.length) {
        return nil;
    }
    NSString* cachePath = [self cachePathFromResourcePath:fileName];
    NSString* tmp = [cachePath stringByDeletingLastPathComponent];
    NSError* error = nil;

    if (![self.fileManager fileExistsAtPath:tmp]) {
        ret = [self.fileManager createDirectoryAtPath:tmp withIntermediateDirectories:YES attributes:nil error:&error];
        if (ret) {
            ret = [data writeToFile:cachePath atomically:YES];
        }
    }
    else {
        ret = [data writeToFile:cachePath atomically:YES];
    }

    return ret ? cachePath : nil;
}

- (NSData*)dataFromCacheStorageWithResourcePath:(NSString*)fileName
{
    NSData* data = nil;
    if (!fileName.length) {
        return data;
    }

    NSString* cachePath = [self cachePathFromResourcePath:fileName];

    data = [NSData dataWithContentsOfFile:cachePath];

    return data;
}

- (NSString*)smallPictureName:(NSString*)fileName
{
    return [NSString stringWithFormat:@"%@%@", kBigPictureNamePrefix, fileName];
}

- (BOOL)deleteDataWithImageName:(NSString*)fileName
{
    BOOL ret = NO;
    if (!fileName.length) {
        return ret;
    }
    NSString* cachePath = [self cachePathFromResourcePath:fileName];
    if ([self.fileManager fileExistsAtPath:cachePath isDirectory:NULL]) {
        ret = [self.fileManager removeItemAtPath:cachePath error:NULL];
    }
    else {
        ret = YES;
    }

    return ret;
}

- (NSString*)cachePathFromResourcePath:(NSString*)fileName
{
    NSString* cachePath = nil;

    NSString* rootPath = [[self cachePathFromResourcePath] stringByAppendingPathComponent:@"picture"];

    cachePath = [[rootPath stringByAppendingPathComponent:fileName] stringByAppendingPathComponent:cachePath];

    return cachePath;
}

- (NSString*)fileCachePathFromResourcePath:(NSString*)fileName
{
    NSString* cachePath = nil;
    
    NSString* rootPath = [[self cachePathFromResourcePath] stringByAppendingPathComponent:@"myDownLoadFiles"];
    
    cachePath = [[rootPath stringByAppendingPathComponent:fileName] stringByAppendingPathComponent:cachePath];
    
    return cachePath;
}

- (NSString*)cachePathFromResourcePath
{
    static NSString* path = nil;
    if (!path) {
        //cache folder
        path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

        //create the folder if it doesn't exist
        if (![self.fileManager fileExistsAtPath:path isDirectory:NULL]) {
            [self.fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:NULL];
        }
    }
    return path;
}

//#pragma mark - static data
//- (BOOL)downloadedStaticData
//{
//    //return NO;
//
//    __block BOOL result = NO;
//    YWLoginUser* loginUser = [YWLoginTool loginUser];
//    NSString* newkey = [NSString stringWithFormat:@"%@%ld", loginUser.companyAccount, (long)loginUser.uniqueId];
//    NSArray* downloadedUsersInCompany = [[NSUserDefaults standardUserDefaults] objectForKey:kDownloadedStaticData];
//    [downloadedUsersInCompany enumerateObjectsUsingBlock:^(NSString* _Nonnull obj, NSUInteger idx, BOOL* _Nonnull stop) {
//        if ([obj isEqualToString:newkey]) {
//            *stop = YES;
//            result = YES;
//        }
//    }];
//
//    return result;
//}
//
//- (void)saveDownloadedStaticData
//{
//    YWLoginUser* loginUser = [YWLoginTool loginUser];
//    NSString* newkey = [NSString stringWithFormat:@"%@%ld", loginUser.companyAccount, (long)loginUser.uniqueId];
//
//    NSMutableArray* array = [NSMutableArray array];
//    NSArray* downloadedUsersInCompany = [[NSUserDefaults standardUserDefaults] objectForKey:kDownloadedStaticData];
//    if (downloadedUsersInCompany) {
//        [array addObjectsFromArray:downloadedUsersInCompany];
//    }
//    [array addObject:newkey];
//
//    [[NSUserDefaults standardUserDefaults] setObject:array forKey:kDownloadedStaticData];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//}

#pragma mark - picture
- (BOOL)savePicturesToDBWithArray:(NSArray*)pictures
{
    return [[YWDBTool shareDBTool] updatePictureWithArray:pictures];
}

- (void)uploadLocalPictureToAliyunOSS:(NSArray*)pictureArray isAvatar:(BOOL)isAvatar complete:(void (^)(BOOL isError, NSArray* uploadPictures))completeBlock{
    __block CGFloat maxUploadCount = 3;
    __block NSMutableArray* blockSucceedPictures = [NSMutableArray array];
    __block BOOL isError = NO;
    __block BOOL isAvatarBlock = isAvatar;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_async(queue, ^{
        dispatch_group_t group = dispatch_group_create();
        [pictureArray enumerateObjectsUsingBlock:^(YWPicture* _Nonnull picture, NSUInteger idx, BOOL* _Nonnull stop) {
            NSString *smallPicPath = [self cachePathFromResourcePath:[self smallPictureName:picture.pictureName]];
            NSString *bigPicPath = [self cachePathFromResourcePath:picture.pictureName];
            //判断图片路径是否存在
            if ([[NSFileManager defaultManager] fileExistsAtPath:smallPicPath] && [[NSFileManager defaultManager] fileExistsAtPath:bigPicPath]) {
                dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    CGFloat uploadSmallPictureCount = 0;
                    if (picture.uploadStatus == YWPictureUploadStatusSuccess) {
                        [blockSucceedPictures addObject:picture];
                    }
                    else {
                        while (uploadSmallPictureCount < maxUploadCount) {
                            uploadSmallPictureCount++;
                            if ([[YWAliyunOSSManager shareManager] uploadPictureSyncWithFilePath:smallPicPath isAvatar:isAvatarBlock]) {
                                if (isAvatarBlock) {
                                    picture.smallPictureUrl = [[YWAliyunOSSManager shareManager] ossSaveAvatarFilePath:[self smallPictureName:picture.pictureName]];
                                }else{
                                    picture.smallPictureUrl = [[YWAliyunOSSManager shareManager] ossSaveFilePath:[self smallPictureName:picture.pictureName]];
                                }
                                
                                isError = NO;
                                break;
                            }
                            else {
                                isError = YES;
                            }
                        }
                        
                        if (!isError) {
                            CGFloat uploadbigPictureCount = 0;
                            while (uploadbigPictureCount < maxUploadCount) {
                                uploadbigPictureCount++;
                                if ([[YWAliyunOSSManager shareManager] uploadPictureSyncWithFilePath:bigPicPath isAvatar:isAvatarBlock]) {
                                    if (isAvatarBlock) {
                                        picture.bigPictureUrl = [[YWAliyunOSSManager shareManager] ossSaveAvatarFilePath:picture.pictureName];
                                    }else{
                                        picture.bigPictureUrl = [[YWAliyunOSSManager shareManager] ossSaveFilePath:picture.pictureName];
                                    }
                                    [blockSucceedPictures addObject:picture];
                                    isError = NO;
                                    break;
                                }
                                else {
                                    isError = YES;
                                }
                            }
                        }
                        picture.uploadStatus = isError ? YWPictureUploadStatusFail : YWPictureUploadStatusSuccess;
                    }
                });
            }else{
                YWLog(@"图片路径不存在");
            }
        }];
        
        // 等待组中的任务执行完毕,回到主线程执行block回调
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            if (completeBlock) {
                completeBlock(isError, blockSucceedPictures);
            }
        });
    });
}
- (void)uploadPatrolPictureToAliyunOSS:(NSArray*)pictureArray complete:(void (^)(BOOL isError, NSArray* uploadPictures))completeBlock{
    __block CGFloat maxUploadCount = 3;
    __block NSMutableArray* blockSucceedPictures = [NSMutableArray array];
    __block BOOL isError = NO;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        dispatch_group_t group = dispatch_group_create();
        [pictureArray enumerateObjectsUsingBlock:^(YWPatrolPicture* _Nonnull picture, NSUInteger idx, BOOL* _Nonnull stop) {
            NSString *smallPicPath = [self cachePathFromResourcePath:[self smallPictureName:picture.pictureName]];
            NSString *bigPicPath = [self cachePathFromResourcePath:picture.pictureName];
            //判断图片路径是否存在
            if ([[NSFileManager defaultManager] fileExistsAtPath:smallPicPath] && [[NSFileManager defaultManager] fileExistsAtPath:bigPicPath]) {
                dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    CGFloat uploadSmallPictureCount = 0;
                    if (picture.uploadStatus == YWPictureRecordUploadStatusSuccess) {
                        [blockSucceedPictures addObject:picture];
                    }
                    else {
                        while (uploadSmallPictureCount < maxUploadCount) {
                            uploadSmallPictureCount++;
                            if ([[YWAliyunOSSManager shareManager] uploadPictureSyncWithFilePath:smallPicPath isAvatar:NO]) {
                                picture.smallUrl = [[YWAliyunOSSManager shareManager] ossSaveFilePath:[self smallPictureName:picture.pictureName]];
                                
                                isError = NO;
                                break;
                            }
                            else {
                                isError = YES;
                            }
                        }
                        
                        if (!isError) {
                            CGFloat uploadbigPictureCount = 0;
                            while (uploadbigPictureCount < maxUploadCount) {
                                uploadbigPictureCount++;
                                if ([[YWAliyunOSSManager shareManager] uploadPictureSyncWithFilePath:bigPicPath isAvatar:NO]) {
                                    picture.bigUrl = [[YWAliyunOSSManager shareManager] ossSaveFilePath:picture.pictureName];
                                    
                                    [blockSucceedPictures addObject:picture];
                                    isError = NO;
                                    break;
                                }
                                else {
                                    isError = YES;
                                }
                            }
                        }
                        picture.uploadStatus = isError ? YWPictureRecordUploadStatusFail : YWPictureRecordUploadStatusSuccess;
                    }
                });
            }else{
                YWLog(@"图片路径不存在");
            }
        }];
        
        // 等待组中的任务执行完毕,回到主线程执行block回调
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            if (completeBlock) {
                completeBlock(isError, blockSucceedPictures);
            }
        });
    });
}
@end
